package com.ok.es.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.ok.common.domain.po.Result;
import com.ok.es.domain.dto.CartoonListDTO;
import com.ok.es.domain.po.OkCartoon;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CartoonEsController
 * @Description 漫画es查询
 * @Author hw
 * @Date 2024/5/14 20:36
 */
@Api(tags = "漫画es接口")
@RestController
@RequestMapping("/cartoon-es")
public class CartoonEsController {

    @Autowired
    private RestHighLevelClient client;

    @ApiOperation("*搜索漫画")
    @GetMapping("/list")
    public Result list(
            @RequestParam Integer pageNo,
            @RequestParam Integer pageSize,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer areaId,
            @RequestParam(required = false) Integer categoryId) throws IOException {

        // 1.创建Request
        SearchRequest request = new SearchRequest("cartoon");
        // 2.组织请求参数
        // 2.1.准备bool查询
        BoolQueryBuilder bool = null;
        if (name != null || categoryId != null || areaId != null) {
            bool = QueryBuilders.boolQuery();
            // 2.2.关键字搜索
            if (name != null) {
                bool.must(QueryBuilders.matchQuery("name", name));
            }
            if (categoryId != null) {
                bool.must(QueryBuilders.matchQuery("categoryId", categoryId));
            }
            // 2.3.国家过滤
            if (areaId != null) {
                bool.filter(QueryBuilders.termQuery("areaId", areaId));
            }
        }

        // 2.3.分页参数
        request.source().from((pageNo - 1) * pageSize).size(pageSize);
        request.source().query(bool);
        // 3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4.解析响应
        List list = handleResponse(response);

        return Result.success(list);
    }


    /*
    解析响应
     */
    private List handleResponse(SearchResponse response) {
        ArrayList<Object> list = new ArrayList<>();
        SearchHits searchHits = response.getHits();
        // 1.获取总条数
        long total = searchHits.getTotalHits().value;
        System.out.println("共搜索到" + total + "条数据");
        // 2.遍历结果数组
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            // 3.得到_source，也就是原始json文档
            String source = hit.getSourceAsString();
            // 4.反序列化并打印
            OkCartoon item = JSONUtil.toBean(source, OkCartoon.class);

            //获取高亮结果
            Map<String, HighlightField> hfs = hit.getHighlightFields();
            if (!CollUtil.isEmpty(hfs)) {
                //有高亮结果，获取name的高亮结果
                HighlightField hf = hfs.get("name");
                if (hf != null) {
                    //获取第一个高亮结果片段，就是商品名称的高亮值
                    String hfName = hf.getFragments()[0].toString();
                    item.setName(hfName);
                }
            }
            System.out.println(item);
            list.add(item);
        }
        return list;
    }

}
